package com.hypo.aop;

import com.hypo.mapper.EmpLoginLogMapper;
import com.hypo.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class EmpLoginLogAspect {
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    /**
     * 记录登录日志信息
     */
    @Around("execution(* com.hypo.controller.LoginController.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        Long costTime = end - start;

        //获取参数对象
        Object[] args = pjp.getArgs();
        //强转成Emp对象
        Emp emp = (Emp) args[0];
        String username = emp.getUsername();
        String password = emp.getPassword();

        //强转Result对象
        Result res = (Result) result;
        //获取成功失败强转
        short code = res.getCode().shortValue();
        //将Data强转LoginInfo
        LoginInfo loginInfo = (LoginInfo) res.getData();
        //判断是否为空
        String token = null;
        if (loginInfo != null) {
            token = loginInfo.getToken();
        }

        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        empLoginLog.setLoginTime(LocalDateTime.now());
        empLoginLog.setIsSuccess(code);
        empLoginLog.setJwt(token);
        empLoginLog.setCostTime(costTime);
        empLoginLogMapper.add(empLoginLog);
        return result;
    }

}
